package main

import (
	"fmt"
	"sort"
)

func main() {
	var map1 map[string]string
	// 使用前先make,声明空间
	map1 = make(map[string]string, 16)
	map1["key1"] = "value1"
	fmt.Println(map1)
	var map2 = make(map[string]string)
	map2["key1"] = "value1"
	fmt.Println(map2)
	var map3 = map[string]string{"k1": "v1", "k2": "v2"}
	fmt.Println(map3)

	var map4 = make(map[string]map[string]string)
	map4["stu1"] = map[string]string{"addr": "sh", "age": "12"}
	map4["stu2"] = map[string]string{"addr": "hn", "age": "13"}
	fmt.Println(map4)
	// map 删除 delete
	delete(map4, "stu1")
	fmt.Println(map4)
	// 删除所有。遍历或者make
	//查找
	v, ok := map4["stu2"]
	if ok {
		fmt.Println(v)
	} else {
		fmt.Println("没有查找到")
	}
	// 遍历
	for k, v := range map2 {
		fmt.Println(k, v)
	}
	map4["stu1"] = map[string]string{"addr": "sh", "age": "12"}
	for k, v := range map4 {
		fmt.Println(k)
		for k2, v2 := range v {
			fmt.Printf("\t k2=%v v2=%v \n", k2, v2)
		}
	}
	fmt.Println("===map 排序===")

	// map 排序
	map5 := make(map[int]int)
	map5[3] = 3
	map5[4] = 4
	map5[2] = 2
	map5[6] = 6
	var keys []int
	for k, _ := range map5 {
		keys = append(keys, k)
	}
	sort.Ints(keys)
	fmt.Println(keys)

	for _, key := range keys {
		fmt.Println(map5[key])
	}
	fmt.Println("=== 结构体===")
	// 结构体

	users := make(map[string]User)
	user1 := User{12, "zw", "sh"}
	user2 := User{13, "ss", "hn"}
	users["u1"] = user1
	users["u2"] = user2
	fmt.Println(users)

	for k, v := range users {
		fmt.Printf("编号:%v \n", k)
		fmt.Printf("姓名:%v \n", v.name)
		fmt.Printf("年龄:%v \n", v.age)
		fmt.Printf("城市:%v \n", v.addr)
		fmt.Println()
	}

	users2 := make(map[string]map[string]string)
	map7 := make(map[string]string)
	map7["zw2"] = "222"
	map7["zw2"] = "zw2"
	users2["zw2"] = map7
	modifyUser(users2, "zw")
	modifyUser(users2, "zw2")
}

func modifyUser(users map[string]map[string]string, name string) {
	if users[name] != nil {
		users[name]["pwd"] = "666"
		fmt.Printf("已存在 %v", users[name])
	} else {
		users[name] = make(map[string]string)
		users[name]["pwd"] = "666"
		users[name]["name"] = name
		fmt.Printf("不存在 %v", users[name])
	}
}

type User struct {
	age  int
	name string
	addr string
}
